//
//
//
//    添加和编辑收货地址
//

#import "BK_my_EditAddressVC.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "BK_my_ShippingAddress.h"
#import "BK_my_ShippingAddressServer.h"
#import "BK_my_ContactPeople.h"
#import "Masonry.h"
#import "BK_my_Area.h"
#import "BK_my_AreaService.h"
#import "BKMyCommon.h"
#import "BK_my_selectedContactPeopleCell.h"
#import "BK_my_locationAddressCell.h"
#import "BK_my_addressSwitchCell.h"
#import "BK_my_detailAddressCell.h"
#import "BK_my_PostCodeCell.h"
#import "BK_Adress_Tool.h"

#define FirstComponent 0
#define SubComponent 1
#define ThirdComponent 2
#define Regax_DetailAddress  @"^[(a-zA-Z0-9\u4E00-\u9FA5)|(-)|(#)|(、)|( )|(（)|(）)|(【)|(】)|([)|(])|(()|())|(-)|(－)|(-)]+$"

@interface BK_my_EditAddressVC ()<ABPersonViewControllerDelegate, ABPeoplePickerNavigationControllerDelegate, ABNewPersonViewControllerDelegate, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource, AddContactPeopleDelegate, locationLabelClickDelegate, detailAddressDelegate, PostCodeDelegate, SwitchDelegate>

@property (nonatomic, copy) Compeletion compeletion;
@property (nonatomic, assign) BOOL isViewVisable;
@property (nonatomic, strong) UIView *showPickerBgView;
@property (nonatomic, strong) UIAlertController *alertVC;
@property (nonatomic, strong) UIButton *saveAndUseButton;//保存按钮
@property (nonatomic, strong) UITableView *editShippingAddressTableView;
@property (nonatomic, strong) UIPickerView *locationPickerView;

@property (nonatomic, strong) NSMutableArray *provinceArray;
@property (nonatomic, strong) NSMutableArray *cityArray;
@property (nonatomic, strong) NSMutableArray *countryArray;

@property (nonatomic, strong) NSString *proviceStr;
@property (nonatomic, strong) NSString *cityStr;
@property (nonatomic, strong) NSString *countryStr;
@property (nonatomic, strong) NSString *proviceCode;
@property (nonatomic, strong) NSString *cityCode;
@property (nonatomic, strong) NSString *countryCode;

@property (nonatomic, strong) NSString *code;

@property (nonatomic, strong) NSString *nameStr;
@property (nonatomic, strong) NSString *phoneStr;
@property (nonatomic, strong) NSString *locationStr;
@property (nonatomic, strong) NSString *detailAddressStr;
@property (nonatomic, strong) NSString *postCodeStr;
@property (nonatomic, strong) NSString *is_defaultAddressType;

@property (nonatomic, strong) NSString *addressID;
@property (nonatomic, assign) BOOL isCancel;
@property (nonatomic, assign) int int_isFirst;//标记值[1表示第一次加载]【确保pikerView的数据只加载一次，防止重复请求】
@property (nonatomic, assign) NSInteger integer_Component_One_row;//第一级菜单点选行数
@property (nonatomic, assign) NSInteger integer_Component_Two_row;//第二级菜单点选行数
@property (nonatomic, assign) NSInteger integer_Component_Three_row;//第三级菜单点选行数
@property (nonatomic, strong) NSArray<SectionModel *> *sectionArray;



@property (nonatomic, strong)UIView *view_back;//盖板    专门针对iOS7手机使用
@end

@implementation BK_my_EditAddressVC

static NSString *editVCSelectedContactPeopleCell = @"editVCSelectedContactPeopleCell";
static NSString *editVCLocationAddressCell = @"editVCLocationAddressCell";
static NSString *editVCDetailAddressCell = @"editVCDetailAddressCell";
static NSString *editVCpostCodeCell = @"editVCpostCodeCell";
static NSString *editVCAddressSwitchCell = @"editVCAddressSwitchCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    if (_isAddShippingAddress) {
        self.title = @"新增收货地址";
    } else {
        self.title = @"编辑收货地址";
    }
    _isCancel = YES;
    [self initialize];
    [self createUI];
    _int_isFirst = 0;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewEndEditing)];
    [self.view addGestureRecognizer:tap];
}

- (void)viewDidLayoutSubviews {
    if ([self.editShippingAddressTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.editShippingAddressTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.editShippingAddressTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.editShippingAddressTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.isViewVisable = YES;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.isViewVisable = NO;
}

- (void)initialize {
    _int_isFirst = 0;
    _is_defaultAddressType = @"0";
    self.provinceArray = [[NSMutableArray alloc] init];
    self.cityArray = [[NSMutableArray alloc] init];
    self.countryArray = [[NSMutableArray alloc] init];
}

- (void)createUI {
    self.editShippingAddressTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.editShippingAddressTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.editShippingAddressTableView.backgroundColor = BK_MY_COLOR_03;
    self.editShippingAddressTableView.delegate = self;
    self.editShippingAddressTableView.dataSource = self;
    [self.view addSubview:self.editShippingAddressTableView];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 74)];
    _saveAndUseButton = [[UIButton alloc] initWithFrame:CGRectZero];
    _saveAndUseButton.layer.cornerRadius = 5.0;
    _saveAndUseButton.backgroundColor = BK_MY_COLOR_01;
    [_saveAndUseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_saveAndUseButton setTitle:@"保存并使用" forState:UIControlStateNormal];
    [self.saveAndUseButton addTarget:self action:@selector(saveAndUseAddress:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:_saveAndUseButton];
    [_saveAndUseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footerView.mas_left).mas_offset(15);
        make.right.equalTo(footerView.mas_right).mas_offset(-15);
        make.height.equalTo(@(44));
        make.centerY.equalTo(footerView.mas_centerY);
    }];
    self.editShippingAddressTableView.tableFooterView = footerView;
    
    
    _view_back = [[UIView alloc]init];
    _view_back.frame=CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    _view_back.backgroundColor=[UIColor blackColor];
    _view_back.alpha=0.3;
    [self.view  addSubview:_view_back];
    _view_back.hidden=YES;
}

- (void)saveAndUseAddress:(UIButton *)sender {
    if (_nameStr.length < 2 || _nameStr.length > 16) {
        [HUD showMessage:@"请输入正确姓名(2-16个字符)"];
        return;
    }
    if (![self isValidateMobile:_phoneStr]) {
        [HUD showMessage:@"请输入正确的手机号码"];
        return;
    }
    if (_proviceStr == nil || [_proviceStr isEqualToString:@""]) {
        [HUD showMessage:@"请选择所在省份"];
        return;
    }
    if (_cityStr == nil || [_cityStr isEqualToString:@""]) {
        [HUD showMessage:@"请选择所在城市"];
        return;
    }
    if (_countryStr == nil || [_countryStr isEqualToString:@""]) {
        [HUD showMessage:@"请选择所在区县"];
        return;
    }
    if (_detailAddressStr == nil || [_detailAddressStr isEqualToString:@""]) {
        [HUD showMessage:@"请输入详细地址"];
        return;
    }
    if ([self checkDetailAddress:_detailAddressStr]) {
        [HUD showMessage:@"您输入的地址中含有非法字符，请修改您的收货地址"];
        return;
    }
    if (_detailAddressStr.length > 50) {
        [HUD showMessage:@"输入地址应小于50字"];
        return;
    }
    if (_postCodeStr.length != 6) {
        [HUD showMessage:@"请输入6位邮政编码"];
        return;
    }
    
    [self.editShippingAddressTableView endEditing:YES];
    _saveAndUseButton.enabled = NO;
//    [HUD showProgress:@"正在保存"];
    [HUD showProgress:nil];
    [self uploadAddressToServer];
}

- (void)uploadAddressToServer {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    if (!_isAddShippingAddress) {//编辑收货地址需要地址id
        [dict setObject:_addressID forKey:@"id"];
    }
    [dict setObject:_nameStr forKey:@"deliver_name"];
    [dict setObject:_phoneStr forKey:@"telephone"];
    if (_isCancel == YES) {//pickerView点击了取消
        [dict setObject:self.address.shippingProvinceName forKey:@"province_name"];
        [dict setObject:self.address.shippingCityName forKey:@"city_name"];
        [dict setObject:self.address.shippingCountyName forKey:@"county_name"];
        [dict setObject:self.address.shippingProvinceCode forKey:@"province_code"];
        [dict setObject:self.address.shippingCityCode forKey:@"city_code"];
        [dict setObject:self.address.shippingCountyCode forKey:@"county_code"];
    } else {
        [dict setObject:_proviceStr forKey:@"province_name"];
        [dict setObject:_cityStr forKey:@"city_name"];
        [dict setObject:_countryStr forKey:@"county_name"];
        [dict setObject:_proviceCode forKey:@"province_code"];
        [dict setObject:_cityCode forKey:@"city_code"];
        [dict setObject:_countryCode forKey:@"county_code"];
    }
    [dict setObject:_is_defaultAddressType forKey:@"is_default"];
    [dict setObject:_postCodeStr forKey:@"post_code"];
    [dict setObject:[BK_Adress_Tool getStr_With_Str:_detailAddressStr] forKey:@"address"];
    
    [dict setObject:@"" forKey:@"fixed_telephone"];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSDictionary *bodyDict = [NSDictionary dictionaryWithObjectsAndKeys:jsonString,@"data", nil];
    if (_isAddShippingAddress) {//新增收货地址
        [BK_my_ShippingAddressServer addShippingAddress:bodyDict callback:^(id obj, NSError *error) {
            _saveAndUseButton.enabled = YES;
            if (error) {
                if (error.code==502) {
                    [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
                    return ;
                }
                [HUD showErrorMessage:error.localizedDescription];
                return;
            }
            NSDictionary *dict = obj;
            BOOL success = [[dict objectForKey:@"success"] boolValue];
            if (success) {
                [HUD showSuccessMessage:@"新增收货地址成功"];
                if (_isCome_OD) {
                    /*
                     * 如果是从订单过来的
                     */
//                    斤
                    [BK_Adress_Tool BK_saveStr:@"Success" withID:@"Add_Address_Success_and_Use"];
                }
                
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    } else {//编辑收货地址
        [BK_my_ShippingAddressServer editShippingAddress:bodyDict :^(id obj, NSError *error) {
            _saveAndUseButton.enabled = YES;
            if (error) {
                if (error.code==502) {
                    [HUD showMessage:@"服务器开小差了，请稍后再试！"];
                }else{
                    [HUD showMessage:error.localizedDescription];
                }
            }
            NSDictionary *dict = obj;
            BOOL success = [[dict objectForKey:@"success"] boolValue];
            if (success) {
                [HUD showSuccessMessage:@"编辑收货地址成功"];
                _address.shippingProvinceCode = _code;
                _address.shippingProvinceName = _proviceStr;
                _address.shippingCityCode = _cityCode;
                _address.shippingCityName = _cityStr;
                _address.shippingCountyCode = _countryCode;
                _address.shippingCountyName = _countryStr;
                _address.shippingDetailAddress = _detailAddressStr;
                _address.shippingPostCode = _postCodeStr;
                _address.isDefaultAddress = [_is_defaultAddressType integerValue];
                _address.shippingTelephone = _phoneStr;
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
}

- (BOOL)checkDetailAddress:(NSString *)searchText{
    searchText=[searchText stringByReplacingOccurrencesOfString:@"[" withString:@""];
    searchText=[searchText stringByReplacingOccurrencesOfString:@"]" withString:@""];
    searchText=[searchText stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSRange range = [searchText rangeOfString:Regax_DetailAddress options:NSRegularExpressionSearch];
    if (range.location != NSNotFound) {
        return NO;//不含有非法字符
    }else{
        return YES;
    }
}

- (BOOL)isValidateMobile:(NSString *)mobile{
    NSString *phoneRegex = @"^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    SectionModel *s = self.sectionArray[section];
    return s.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel *s = self.sectionArray[indexPath.section];
    CellModel *cel = s.cells[indexPath.row];
    return cel.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel *s = self.sectionArray[indexPath.section];
    CellModel *row = s.cells[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:row.reuseIdentifier];
   
    if (cell == nil) {
        cell = [[NSClassFromString(row.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:row.reuseIdentifier];
    }
    if ([cell respondsToSelector:@selector(initlizeValue:)]) {
        [cell performSelector:@selector(initlizeValue:) withObject:row];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    SectionModel *s = self.sectionArray[indexPath.section];
//    CellModel *row = s.cells[indexPath.row];
//    if ([row.className isEqualToString:@"BK_my_locationAddressCell"]) {
//        /*
//         * picker
//         */
//
//        _int_isFirst++;
//        if (_int_isFirst == 1) {
//            //        [HUD showProgress:@"正在加载"];
//            [HUD showProgress:nil];
//            [self.view endEditing:YES];
//            [self initlizePickerViewData:[tableView cellForRowAtIndexPath:indexPath]];
//        } else {
//            [self showPickerView:[tableView cellForRowAtIndexPath:indexPath]];
//        }
//        
//    }
    
}

- (void)addContactPeople:(BK_my_selectedContactPeopleCell *)cell inputEnd:(BK_my_ShippingAddress *)address {
    self.nameStr = cell.nameTextfield.text;
    self.phoneStr = cell.phoneTextfield.text;
}

- (void)addContactPeople:(BK_my_selectedContactPeopleCell *)cell chooseContactPeople:(Compeletion)compeletion {
    ABPeoplePickerNavigationController *peoplePickerNav = [[ABPeoplePickerNavigationController alloc] init];
   [[UINavigationBar appearance] setTintColor:BK_MY_COLOR_01];
    [peoplePickerNav.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:20]}];
    peoplePickerNav.peoplePickerDelegate = self;
    self.compeletion = compeletion;
    [self presentViewController:peoplePickerNav animated:YES completion:nil];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    if (phone) {
        self.compeletion(person);
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person NS_DEPRECATED_IOS(2_0, 8_0){
    self.compeletion(person);
    [self dismissViewControllerAnimated:YES completion:nil];
    return YES;
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
    self.compeletion(person);
    BK_my_ContactPeople *people = [[BK_my_ContactPeople alloc] init];
    [people parsePerson:person];
    self.nameStr = people.name;
    self.phoneStr = people.telephone;
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }
    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    self.compeletion(person);
    BK_my_ContactPeople *people = [[BK_my_ContactPeople alloc] init];
    [people parsePerson:person];
    self.nameStr = people.name;
    self.phoneStr = people.telephone;
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
    return NO;
}

- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(nullable ABRecordRef)person{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark-如果不写此方法，点击取消无反应，程序会崩溃(ios7)
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)switchStatusInCell:(UISwitch *)switchStatus {
    self.is_defaultAddressType = [NSString stringWithFormat:@"%d", switchStatus.on];
}

- (void)detailAddressInformation:(NSString *)detailAddress {
    self.detailAddressStr = detailAddress;
}

- (void)postCodeInformation:(NSString *)postCode {
    self.postCodeStr = postCode;
}

- (void)clickLocationLabelShowPickerViewInViewController:(BK_my_locationAddressCell *)cell {
    _int_isFirst++;
    if (_int_isFirst == 1) {
//        [HUD showProgress:@"正在加载"];
        [HUD showProgress:nil];
        [self.view endEditing:YES];
        [self initlizePickerViewData:cell];
    } else {
        [self showPickerView:cell];
    }
}

- (void)showPickerView:(BK_my_locationAddressCell *)cell {
    [self.view endEditing:YES];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        
        
        

        _view_back.hidden=NO;
        self.showPickerBgView = [[UIView alloc] initWithFrame:CGRectMake(10, self.view.frame.size.height - 280-10, self.view.size.width-20, 280)];
        self.showPickerBgView.layer.cornerRadius = 8;
        self.showPickerBgView.layer.masksToBounds = YES;
        self.showPickerBgView.layer.borderColor = [[UIColor whiteColor] CGColor];
        [self.view addSubview:self.showPickerBgView];

        self.showPickerBgView.backgroundColor = [UIColor whiteColor];

        //        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(viewEndEditing)];
//        [self.showPickerBgView addGestureRecognizer:panGesture];
        self.locationPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-20, 40)];
        self.locationPickerView.delegate = self;
        self.locationPickerView.dataSource = self;
        [self.showPickerBgView addSubview:self.locationPickerView];
        
        
        
        
        
        UIView * view_line_1=[[UIView alloc]init];
        view_line_1.backgroundColor=RGBCOLOR(230, 230, 230, 1);
        [self.showPickerBgView addSubview:view_line_1];
        [view_line_1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.showPickerBgView.mas_left).offset(0);
            make.right.equalTo(self.showPickerBgView.mas_right).offset(0);
            make.height.equalTo(@(1));
            make.bottom.equalTo(self.showPickerBgView.mas_bottom).offset(-106);
        }];
        
        
        
        
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.showPickerBgView addSubview:button1];
        button1.tag = 1;
        button1.layer.cornerRadius = 5;
        [button1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.showPickerBgView.mas_left).offset(15);
            make.right.equalTo(self.showPickerBgView.mas_right).offset(-15);
            make.bottom.equalTo(self.showPickerBgView.mas_bottom).offset(-60);
            make.height.equalTo(@(40));
        }];
        [button1 setTitle:@"确认" forState:UIControlStateNormal];
        
        button1.backgroundColor = [UIColor whiteColor];
        
        [button1 setTitleColor:self.view.tintColor forState:UIControlStateNormal];
        
        
        
        [button1 addTarget:self action:@selector(action_OK_ios7) forControlEvents:UIControlEventTouchUpInside];
        
        
        UIView * view_line_2=[[UIView alloc]init];
        view_line_2.backgroundColor=RGBCOLOR(230, 230, 230, 1);
        [self.showPickerBgView addSubview:view_line_2];
        [view_line_2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.showPickerBgView.mas_left).offset(0);
            make.right.equalTo(self.showPickerBgView.mas_right).offset(0);
            make.top.equalTo(button1.mas_bottom).offset(5);
            make.height.equalTo(@(1));
        }];

        
        UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.showPickerBgView addSubview:button2];
        button2.tag = 2;
        button2.layer.cornerRadius = 5;
        [button2 addTarget:self action:@selector(action_cancel_ios7) forControlEvents:UIControlEventTouchUpInside];
        [button2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.showPickerBgView.mas_left).offset(15);
            make.right.equalTo(self.showPickerBgView.mas_right).offset(-15);
            make.top.equalTo(button1.mas_bottom).offset(10);
            make.height.equalTo(@(40));
        }];
        [button2 setTitle:@"取消" forState:UIControlStateNormal];
  
        [button2 setTitleColor:self.view.tintColor forState:UIControlStateNormal];

        button2.backgroundColor = [UIColor whiteColor];
//        button2.backgroundColor = BK_MY_COLOR_01;
        
        
        
    } else {
        self.alertVC = [UIAlertController alertControllerWithTitle:@"\n\n\n\n\n\n\n\n\n" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        self.locationPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(self.alertVC.view.frame.origin.x, self.alertVC.view.frame.origin.y + 20, self.alertVC.view.frame.size.width - 20, 180)];
        self.locationPickerView.delegate = self;
        self.locationPickerView.dataSource = self;

        UIAlertAction *alertAction_OK = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            cell.locationLabel.text = [NSString stringWithFormat:@"%@%@%@", self.proviceStr, self.cityStr, self.countryStr];
            _isCancel = NO;
        }];
        UIAlertAction *alertAction_cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            _isCancel = YES;
        }];
        [self.alertVC.view addSubview:self.locationPickerView];
        [self.alertVC addAction:alertAction_OK];
        [self.alertVC addAction:alertAction_cancel];
        if ([self isViewVisable]) {
           // [self.view endEditing:YES];
            [self presentViewController:self.alertVC animated:YES completion:nil];
        }
    }
}

- (void)initlizePickerViewData:(BK_my_locationAddressCell *)cell {
    dispatch_queue_t queue = dispatch_queue_create("ANDREW", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        [BK_my_AreaService searchAllAreaInfo:nil callback:^(id obj, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (obj) {
                    [HUD dismiss];
                    NSDictionary *dict = obj;
                    NSDictionary *data_dict = dict[@"data"];
                    NSArray *arr = data_dict[@"returnList"];
                    for (NSDictionary *provice in arr) {
                        [_provinceArray addObject:provice];
                    }
                    
                    
                    /*
                     * 对后台屏蔽港澳台进行处理
                     */
                    if (_provinceArray.count>31) {
                        if (_provinceArray.count>31) {//后台变换数据库    防止崩溃
                            [_provinceArray removeObjectAtIndex:31];
                        }
                        if (_provinceArray.count>32) {
                            [_provinceArray removeObjectAtIndex:32];
                        }
                        
                        [_provinceArray removeLastObject];
                        
                    }
                    [self showPickerView:cell];
                    
                }
                [self.locationPickerView reloadComponent:0];
                [self loadComponent_one:0];
                [self loadComponent_two:0];
                [self loadComponent_three:0];
            });
        }];
    });
}

- (void)action_OK_ios7 {
    _isCancel = NO;
    BK_my_locationAddressCell *cell = [self.editShippingAddressTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    cell.locationLabel.text = [NSString stringWithFormat:@"%@%@%@", self.proviceStr, self.cityStr, self.countryStr];
    _view_back.hidden=YES;
    [self.showPickerBgView removeFromSuperview];
}

- (void)action_cancel_ios7 {
    _isCancel = YES;
    _view_back.hidden=YES;
    [self.showPickerBgView removeFromSuperview];
}

- (void)viewEndEditing {
    [self.view endEditing:YES];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == FirstComponent) {
        return self.provinceArray.count;
    }
    if (component == SubComponent) {
        if (_cityArray.count > 0) {
            return self.cityArray.count;
        } else {
            return 0;
        }
    }
    if (component == ThirdComponent) {
        if (_countryArray.count > 0) {
            return self.countryArray.count;
        } else {
            return 0;
        }
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == FirstComponent) {
        NSDictionary *dict = _provinceArray[row];
        NSString *name = dict[@"name"];
        self.proviceStr = name;
        self.proviceCode = dict[@"code"];
        return name;
    }
    if (component == SubComponent) {
        BK_my_Area *area = _cityArray[row];
        self.cityStr = area.areaName;
        _cityCode = area.areaCode;
        return area.areaName;
    }
    if (component == ThirdComponent) {
        BK_my_Area *area = _countryArray[row];
        self.countryStr = area.areaName;
        _countryCode = area.areaCode;
        return area.areaName;
    }
    return nil;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        _integer_Component_One_row = row;
        [self loadComponent_one:row];
    }
    if (component == 1) {
        _integer_Component_Two_row = row;
        [self loadComponent_two:row];
    }
    if (component == ThirdComponent) {
        _integer_Component_Three_row = row;
        [self loadComponent_three:row];
    }
}

- (void)loadComponent_one:(NSInteger)row {
    NSDictionary *dict = _provinceArray[row];
    _proviceCode = [NSString stringWithFormat:@"%@",dict[@"code"]];
    self.proviceStr = dict[@"name"];
    NSArray *arr = dict[@"subArea"];
    NSDictionary *data = arr[0];
    _cityCode = data[@"code"];
    
    if (arr) {
        NSMutableArray *muArrayCitys = [[NSMutableArray alloc] init];
        for (int i = 0; i < [arr count]; i++) {
            NSDictionary *area_dict = arr[i];
            BK_my_Area *area = [[BK_my_Area alloc] init];
            area.areaCode = [area_dict objectForKey:@"code"];
            area.areaName = [area_dict objectForKey:@"name"];
            [muArrayCitys addObject:area];
        }
        _cityArray = muArrayCitys;
        [self.locationPickerView reloadComponent:1];
    } else {
        [self loadCityData];
    }
    [self.locationPickerView selectRow:0 inComponent:1 animated:NO];
    
    if (arr) {
        NSMutableArray *muArr = [[NSMutableArray alloc] init];
        NSArray *arr_county = data[@"subArea"];
        for (int i = 0; i < [arr_county count]; i++) {
            NSDictionary *area_dict = arr_county[i];
            BK_my_Area *area = [[BK_my_Area alloc] init];
            area.areaName = [area_dict objectForKey:@"name"];
            area.areaCode = [area_dict objectForKey:@"code"];
            [muArr addObject:area];
        }
        _countryArray = muArr;
        [self.locationPickerView reloadComponent:2];
    } else {
        [self loadCountyData];
    }
}

- (void)loadComponent_two:(NSInteger)row {
    BK_my_Area *area = _cityArray[row];
    _cityCode = area.areaCode;
    self.cityStr = area.areaName;
    if (_integer_Component_One_row && _integer_Component_Two_row) {
        NSDictionary *dict = _provinceArray[_integer_Component_One_row];
        NSArray *arr = dict[@"subArea"];
        NSDictionary *dict_county = arr[_integer_Component_Two_row];
        NSMutableArray *muArr = [[NSMutableArray alloc] init];
        NSArray *arr_county = dict_county[@"subArea"];
        for (int i = 0; i < [arr_county count]; i++) {
            NSDictionary *area_dict = arr_county[i];
            BK_my_Area *ar = [[BK_my_Area alloc] init];
            ar.areaCode = [area_dict objectForKey:@"code"];
            ar.areaName = [area_dict objectForKey:@"name"];
            [muArr addObject:ar];
        }
        _countryArray = muArr;
        [self.locationPickerView reloadComponent:2];
    } else {
        [self loadCountyData];
    }
    [self.locationPickerView selectRow:0 inComponent:2 animated:NO];
}

- (void)loadComponent_three:(NSInteger)row {
    BK_my_Area *area = _countryArray[row];
    self.countryStr = area.areaName;
    self.countryCode = area.areaCode;
}

- (void)loadCityData {
    dispatch_queue_t queue = dispatch_queue_create("CITY", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
       [BK_my_AreaService searchCity:_code callback:^(id obj, NSError *error) {
           dispatch_async(dispatch_get_main_queue(), ^{
               if (obj) {
                   _cityArray = obj;
               }
               [self.locationPickerView reloadComponent:1];
           });
       }];
    });
}

- (void)loadCountyData {
    [BK_my_AreaService searchSquare:_cityCode callback:^(id obj, NSError *error) {
        if (obj) {
            _countryArray = obj;
        }
        [self.locationPickerView reloadComponent:2];
    }];
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 40;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return self.locationPickerView.bounds.size.width / 3 - 6;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *pickerLabel = (UILabel *)view;
    if (!pickerLabel) {
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        pickerLabel.font = [UIFont systemFontOfSize:16];
    }
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

- (void)dict:(NSDictionary *)dict {
    NSString *type = dict[@"isAdd"];
    if ([type boolValue] == 1) {
        self.isShowSwitch = YES;
        self.isAddShippingAddress = YES;
    } else {
        BK_my_ShippingAddress *shippingAddress = [[BK_my_ShippingAddress alloc] init];
        NSString * str = [dict objectForKey:@"id"];
        shippingAddress.shippingAddressID = str;
        shippingAddress.consigneeName = [dict objectForKey:@"deliver_name"];
        shippingAddress.shippingProvinceName = [dict objectForKey:@"province_name"];
        shippingAddress.shippingCityName = [dict objectForKey:@"city_name"];
        shippingAddress.shippingCountyName = [dict objectForKey:@"county_name"];
        shippingAddress.shippingDetailAddress = [dict objectForKey:@"address"];
        shippingAddress.shippingPostCode = [dict objectForKey:@"post_code"];
        shippingAddress.shippingAddressIsDefault = [dict objectForKey:@"is_default"];
        shippingAddress.shippingTelephone = [dict objectForKey:@"telephone"];
        shippingAddress.shippingFixedTelephone = [dict objectForKey:@"fixed_telephone"];
        shippingAddress.shippingProvinceCode = [dict objectForKey:@"province_code"];
        shippingAddress.shippingCityCode = [dict objectForKey:@"city_code"];
        shippingAddress.shippingCountyCode = [dict objectForKey:@"county_code"];
        self.isShowSwitch = ![shippingAddress.shippingAddressIsDefault boolValue];
        self.address = shippingAddress;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (NSArray<SectionModel *> *)sectionArray {
    CellModel *selectedPeopleCell = [CellModel cellModelWithTitle:@"收 货 人 :" subTitle:@"联系方式:" image:@"BK_my_addressAddPeople" sel:nil];
    selectedPeopleCell.height = 90;
    selectedPeopleCell.reuseIdentifier = editVCSelectedContactPeopleCell;
    selectedPeopleCell.className = @"BK_my_selectedContactPeopleCell";
    selectedPeopleCell.delegate = self;
    
    CellModel *location = [CellModel cellModelWithTitle:@"所在地区:" sel:nil];
    location.height = 48;
    location.reuseIdentifier = editVCLocationAddressCell;
//    location.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    location.className = @"BK_my_locationAddressCell";
    location.delegate = self;
    
    CellModel *address = [CellModel cellModelWithTitle:@"详细地址:" sel:nil];
    address.height = 50;
    address.reuseIdentifier = editVCDetailAddressCell;
    address.className = @"BK_my_detailAddressCell";
    address.delegate = self;
    
    CellModel *postCode = [CellModel cellModelWithTitle:@"邮政编码:" sel:nil];
    postCode.height = 50;
    postCode.reuseIdentifier = editVCpostCodeCell;
    postCode.className = @"BK_my_PostCodeCell";
    postCode.delegate = self;
    
    //从编辑按钮进来cell有内容
    if (!self.isAddShippingAddress) {
        selectedPeopleCell.selectorString = self.address.shippingTelephone;
        selectedPeopleCell.userInfo = self.address.consigneeName;
        location.selectorString = [NSString stringWithFormat:@"%@%@%@", self.address.shippingProvinceName,self.address.shippingCityName, self.address.shippingCountyName];
        address.selectorString = self.address.shippingDetailAddress;
        postCode.selectorString = self.address.shippingPostCode;
        //拿到信息为了保存（进来后没有做任何编辑直接点击了保存）
        self.nameStr = self.address.consigneeName;
        self.phoneStr = self.address.shippingTelephone;
        self.locationStr = location.selectorString;
        self.detailAddressStr = self.address.shippingDetailAddress;
        self.postCodeStr = self.address.shippingPostCode;
        self.addressID = self.address.shippingAddressID;
        
        self.proviceStr = self.address.shippingProvinceName;
        self.cityStr = self.address.shippingCityName;
        self.countryStr = self.address.shippingCountyName;
        self.proviceCode = self.address.shippingProvinceCode;
        self.cityCode = self.address.shippingCityCode;
        self.countryCode = self.address.shippingCountyCode;
        self.is_defaultAddressType = self.address.shippingAddressIsDefault;
    }
    if (self.isShowSwitch) {
        CellModel *switchCell = [CellModel cellModelWithTitle:@"设为默认地址" sel:nil];
        switchCell.height = 51;
        switchCell.reuseIdentifier = editVCAddressSwitchCell;
        switchCell.className = @"BK_my_addressSwitchCell";
        switchCell.delegate = self;
        
        SectionModel *sectionM = [SectionModel sectionModelWithTitle:nil cells:@[selectedPeopleCell, location, address, postCode, switchCell]];
        return @[sectionM];
    } else {
        SectionModel *sectionModel = [SectionModel sectionModelWithTitle:nil cells:@[selectedPeopleCell, location, address, postCode]];
        return @[sectionModel];
    }
}
@end
